var tbody = document.querySelector('#list tbody');
var selectAll = document.querySelector(".select-all input");
var singSlecet = document.getElementsByClassName('singslecet');

let tableData= [];


//全选
selectAll.onclick = function (){
    if(selectAll.checked) {
        for(var i = 0; i < singSlecet.length; i++) {
            singSlecet[i].checked = true;
        }
        tableData.map(function (item) {
            selectedList.push(item.bookId);//被选中的数组id，方便后面删除
        })
    } else {
        for(var i = 0; i < singSlecet.length; i++) {
            singSlecet[i].checked = false;
        }
        selectedList = [];
    }
}

//单选
// 单个处理
$(document).ready(function () {//页面节点未加载出来，获取不到节点，所以加$(document).ready(function ()
    for(var j = 0; j < singSlecet.length; j++) {
        singSlecet[j].onclick = function() {
            for(var x = 0; x < singSlecet.length; x++) {
                // 只要有一个没有选中，则全选应该取消，否则全选应该选中
                if(!singSlecet[x].checked) {
                    selectAll.checked = false;
                    break; // 进入 if 后，break 后的代码不会执行
                }
                selectAll.checked = true;
            }
        }
    }
})

// 当前选中的数据ID
var selectedList = [];



//点击了又取消
function handleChange(checked, id) {//单选框发生改变触发的函数
    if (checked){
        selectedList.push(id);
    }else {//取消了一个
        selectedList = selectedList.filter(function (value) {
            return value !== id;//获取除了取消剩下的数据
        })
    }
}

//确认是否删除模态框
function deleteItem() {
    if (selectedList.length === 0)return;//在没有选中数据的状态时不触发模态框
    layer.open({
        content: '请问是否确认删除该书籍'
        ,btn: ['确认', '取消']
        ,yes: function(index, layer){
            $.ajax({
                url: '/books/del',
                method: 'POST',
                data: {
                    idArr: selectedList.join(",")
                }
            })
                .done(function () {
                    initBook();
                    layer.close(index);
                })
                .fail(function (err) {
                    console.log('请求失败：', err);
                });
        }
        ,btn2: function(index, layero){
            //按钮【按钮二】的回调

            //return false 开启该代码可禁止点击该按钮关闭
        }
        ,cancel: function(){
            //右上角关闭回调

            //return false 开启该代码可禁止点击该按钮关闭
        }

    });
}

// 渲染
function renderTable(data) {
    tbody.innerHTML = ''; // 先清空
    for (var i = 0; i < data.length; i++) {
        var tr = document.createElement('tr');
         tr.innerHTML = `
          <td class="radio-box"><input class="singslecet" type="checkbox" onchange="handleChange(this.checked, ${data[i].bookId})"/></td>
          <td>${data[i].bookName}</td>
          <td>${data[i].bookSubject}</td>
          <td>${data[i].bookAuthor}</td>
          <td>${data[i].bookPublish}</td>
          <td>${data[i].bookPrice}</td>
          <td>${data[i].bookPosition}</td>
          <td>${data[i].bookTime}</td>
          <td><span style="cursor:pointer" data-edit=${data[i].bookId}>编辑</span></td>
          <td><span style="margin-left: -50%;cursor:pointer" data-describe=${data[i].bookId}>查看</span></td>
       
    `;
        tbody.appendChild(tr);
    }
    tbody.onclick = function (e) {
        // 点击编辑按钮时
        if (e.target.dataset.edit) {
            parent.EditData = JSON.parse(e.target.dataset.edit);
            var url = location.href;
            url = url.substring(0, url.lastIndexOf("/"));
            window.location.href = `${url}/addbook.html`;
        }
        // 点击查看按钮时
        if (e.target.dataset.describe) {
            parent.DescribeData = JSON.parse(e.target.dataset.describe);
            var url = location.href;
            url = url.substring(0, url.lastIndexOf("/"));
            window.location.href = `${url}/describe.html`;
        }
    }
}

function initBook(){
    $.ajax({
        url: '/books/get',
        method: 'GET',
        data: {
            current: 1,
            pageSize: 20
        }
    })
        .done(function (res) {
            tableData = res.data;
            renderTable(res.data);
        })
        .fail(function (err) {
            console.log('请求失败：', err);
        });
}
initBook();
// 事件委托-删除
$('nav').on('click', '.del', function () {
    // console.log($(this).attr('data-studentid'));
    const bookId = $(this).attr('data-bookid');
    /*$.ajax({
        url: '/books/del',
        method: 'POST',
        data: {
            bookId: bookId
        }
    })
        .done(function (data) {
            layer.msg(data.msg);
            initStudent();
        })
        .fail(function (err) {
            console.log(err);
            layer.msg(err.msg);
        })*/
});

// 事件委托-查看
$('nav').on('click', '.view', function () {
    const bookId = $(this).attr('data-bookid');

    parent.editIframe('book_edit.html?bookid=' + bookId + '&view=1');
});

// 事件委托-编辑
$('nav').on('click', '.edit', function () {
    const bookId = $(this).attr('data-bookid');

    parent.editIframe('book_edit.html?bookid=' + bookId);
});

// 新增图书
$('nav').on('click', function () {
    parent.editIframe('book_edit.html');
});

// renderTable();//刷新更改后的界面

//点击跳转页面
function pageJump() {
    var url = location.href;
    url = url.substring(0, url.lastIndexOf("/"));
    window.location.href = `${url}/addbook.html`;
}


var addBook = document.getElementsByClassName('add-book')[0];
addBook.onclick = pageJump


//id相同，每一条数据对应一个编辑页内容
function editBooks(param) {
    data.forEach(function (item, index) {
        if (item.id === parent.EditData.id) {
            data[index] = param;
        }
    })
}


/*//修改、新增
function addBooks() {
    var form = document.getElementById("entryForm");
    var formData = new FormData(form);//实例化一个构造函数
    var date = new Date();
    if (!(formData.get("name") && formData.get("id") && formData.get("description") && formData.get("author") && formData.get("publish") && formData.get("price") && formData.get("position"))) {
        alert("请完善信息");
        return;
    }
    const param = {
        id: Number(formData.get("id")),
        name: formData.get("name"),
        subject: "小说",
        author: formData.get("author"),
        publish: formData.get("publish"),
        price: Number(formData.get("price")),
        position: formData.get("position"),
        time: `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`,
        description: formData.get("description"),
    }
    if (parent.EditData && Object.keys(parent.EditData).length > 0) {
        editBooks(param);
    }else {//反之是空的，说明是新增的，就用新增的方法
        $.ajax({
            url: '/books/add',
            method: 'POST',
            data: {
                name: "1",
                subject: "小说",
                author: "11",
                publish: "232",
                price: 20,
                position: "111",
                time: `2021-3-10`,
            }
        })
            .done(function (res) {
                console.log(res);
            })
            .fail(function (err) {
                console.log('请求失败：', err);
            });
    }
    parent.EditData = {};
    var url = location.href;
    url = url.substring(0, url.lastIndexOf("/"));
    window.location.href = `${url}/dxm-index.html`;
}*/






